import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

import java.sql.*;
import java.util.ArrayList;

/**
 * This creates the Log-In screen. User will enter password and identify their
 * position.
 * 
 * @author Mike Jones
 * @version 1.0
 */
public class LogIn extends JPanel {

	private JPanel p1;
	private JPanel p2;
	private JPanel p3;
	private JPanel passwordPanel;
	private JPanel displayPanel;
	private JPanel exitPanel;

	private JButton exitButton;
	private JButton numButton;
	private JButton clear;
	public String idTyped = "";
	private JTextField input;
	public int loginCount = 0;

	private Toolkit tk = Toolkit.getDefaultToolkit();

	/**
	 * Holds the values for the maximum height and width for the user screen
	 * size.
	 */
	private int screenWidth = (int) tk.getScreenSize().getWidth();
	private int screenHeight = ((int) (tk.getScreenSize().getHeight()));

	/**
	 * Constructor - sets up background color and calls to create panels/images
	 */
	public LogIn() {
		setLayout(new GridLayout(1, 3));
		createP1();
		add(p1);
		createP2();
		add(p2);
		createP3();
		add(p3);
		// PopUp p = new PopUp();
		// p.runReservation();
	}// End of Constructor

	/**
	 * Creates the first panel which only includes the UNCW seahawk image
	 */
	private void createP1() {
		p1 = new JPanel();
		p1.setLayout(new BorderLayout());
		p1.setBackground(GUI.teal);
		BufferedImage seahawk;
		try {
			seahawk = ImageIO.read(new File("UNCW.png"));
			JLabel labelUNCW = new JLabel(new ImageIcon(seahawk));
			p1.add(labelUNCW, BorderLayout.NORTH);
		} catch (IOException e) {
			System.out.println("An error has occurred in Panel One");
		}
	}// End createP1 method

	/**
	 * Creates the second panel which contains the num pad to enter a password,
	 * a text field box to display the value, and a clear option
	 */
	private void createP2() {
		p2 = new JPanel();
		p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
		p2.setBackground(GUI.teal);
		displayPanel();
		p2.add(Box.createRigidArea(new Dimension(0, screenHeight / 6)));
		p2.add(displayPanel);
		passwordPanel();
		p2.add(passwordPanel);
		p2.add(Box.createRigidArea(new Dimension(0, screenHeight / 6)));
		createExitButton();
		p2.add(exitPanel);
		p2.add(Box.createRigidArea(new Dimension(0, screenHeight / 6)));
	}// End createP2 method

	/**
	 * Creates the third panel which only includes the tealServ image
	 */
	private void createP3() {
		p3 = new JPanel();
		p3.setLayout(new BorderLayout());
		p3.setBackground(GUI.teal);
		BufferedImage logo;
		try {
			logo = ImageIO.read(new File("tealServ.png"));
			JLabel logoLabel = new JLabel(new ImageIcon(logo));
			p3.add(logoLabel, BorderLayout.SOUTH);
		} catch (IOException e) {
			System.out.println("An error has occurred in Panel Three");
		}
	}// End createP3 method

	/**
	 * Creates the password Panel (p2) which uses a for loop to iterate through
	 * the 9 numbers in the number pad
	 */
	private void passwordPanel() {
		passwordPanel = new JPanel(new GridLayout(3, 3));
		for (int i = 1; i < 10; i++) {
			createNumButton(i);
		}
	}// End of passwordPanel method

	/**
	 * Creates the actual individual buttons for the number pad
	 * 
	 * @param a
	 *            - a number 1-9
	 */
	private void createNumButton(int a) {
		String num = Integer.toString(a);
		numButton = new JButton(num);
		numButton.setFont(new Font("Arial", Font.PLAIN, 80));
		numButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				idTyped += a;
				input.setText(idTyped);
				loginCount++;
				if (loginCount == 4)
					attemptLogin(idTyped);
			}
		});

		passwordPanel.add(numButton);
	}// End createJButton method

	/**
	 * Calls the database to see if the login is valid.
	 * 
	 * @param id
	 *            The id that the user entered.
	 */
	protected void attemptLogin(String id) {
		Integer idInt = Integer.parseInt(id);
		int jobCode = 0;
		String name = "Error";

		// Database call
		Connection c = null;

		if (checkID(idInt)) {
			try {
				c = SqliteHelper.getConn();

				Statement loginStatement = c.createStatement();
				String loginQuery = "SELECT * FROM Employee WHERE Employee.Employee_ID = "
						+ idInt + ";";

				ResultSet results = loginStatement.executeQuery(loginQuery);

				jobCode = results.getInt("Job_Code");
				name = results.getString("FullName");

			} catch (Exception e) {
				System.err.println("Database Call Failure in attemptLogin.");
				System.err.println(e.getClass().getName() + ": "
						+ e.getMessage());
			}
			GUI login = new GUI(idInt, jobCode, name);
			StartSystem.closeFrame();
		} else {
			// Increase size of the buttons
			UIManager.put("OptionPane.buttonFont", new FontUIResource(new Font(
					"ARIAL", Font.PLAIN, 40)));
			// Increase size of the textfont
			UIManager.put("OptionPane.messageFont", new FontUIResource(
					new Font("ARIAL", Font.PLAIN, 40)));

			JOptionPane.showMessageDialog(null,
					"Incorrect employee ID entered.", "ID error",
					JOptionPane.PLAIN_MESSAGE, null);
			clearInput();

		}
		// End Database call
	}

	/**
	 * Creates the first display Panel (p2) which contains the text field to
	 * display the password and the clear button
	 */
	private void displayPanel() {
		displayPanel = new JPanel(new FlowLayout());
		displayPanel.setBackground(GUI.teal);
		createNumDisplay();
		displayPanel.add(input);
		createClear();
		displayPanel.add(clear);
	}// End displayPanel method

	/**
	 * Creates a JTextField called input to display the password
	 */
	private void createNumDisplay() {
		input = new JTextField(10);
		input.setFont(new Font("Arial", Font.PLAIN, 30));
		input.setEditable(false);
	}// End createNumDisplay method

	/**
	 * Creates the clear button to clear the password
	 */
	private void createClear() {
		clear = new JButton("Clear");
		clear.setFont(new Font("Arial", Font.PLAIN, 30));
		clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearInput();
			}
		});
	}// End createClear method

	protected void clearInput() {
		idTyped = "";
		input.setText(idTyped);
		loginCount = 0;
		// TODO Auto-generated method stub

	}

	/**
	 * Checks if the ID given appears in the database.
	 * 
	 * @param id
	 *            The ID given by the user.
	 * @return True if ID exists in database, False if not.
	 */
	private boolean checkID(int id) {
		Connection c = null;
		try {
			c = SqliteHelper.getConn();
			Statement loginStatement = c.createStatement();
			String loginQuery = "SELECT * FROM Employee WHERE Employee.Employee_ID = "
					+ id + ";";

			ResultSet results = loginStatement.executeQuery(loginQuery);
			if (!results.isBeforeFirst()) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			System.err.println("Database Call Failure in checkID.");
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			return false;
		}

	}

	/**
	 * Will exit the program
	 */
	private void createExitButton(){
		exitPanel = new JPanel();
		exitPanel.setBackground(GUI.teal);
		exitButton = new JButton("System Exit");
		exitButton.setFont(new Font("Arial", Font.PLAIN, 50));
		exitButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		exitPanel.add(exitButton);
	}//End createExitButton
	
}// End of Class
